package cn.pangza.log.aspect;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@Aspect
@ConditionalOnProperty(name={"log.aspect.enable"}, havingValue = "true", matchIfMissing = true)
public class LogAspect {

    //  定义切点
    @Pointcut("execution(* cn.pangza.*.controller.*Controller.*(..)) || execution(* cn.pangza.*.service.*Service.*(..))")
    private void pointCut() {}

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 获取参数
        Object[] args = point.getArgs();
        Object json = JSONObject.toJSON(args);
        // 方法
        MethodSignature signature = (MethodSignature) point.getSignature();
        // 类名+方法名
        String methodName = signature.getDeclaringType().getName() + "." + signature.getName();
        log.info("{}, param: {}", methodName, json.toString());
        Long startTime = System.currentTimeMillis();
        Object proceed = point.proceed();
        Object responseJson = JSONObject.toJSON(proceed);
        Long endTime = System.currentTimeMillis();

        log.info("方法: {}, 方法耗时: {}, response: {}", methodName, endTime-startTime, responseJson);
        return proceed;
    }
}